<?php

// 测试修复后的 me 接口
echo "🧪 测试 me 接口修复\n";
echo "=======================\n\n";

// 测试 me 接口（需要认证，这里模拟无认证的情况）
echo "1. 测试 me 接口响应结构...\n";

// 模拟一个简单的请求到 me 接口
$ch = curl_init('http://127.0.0.1:8000/api/auth/me');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "   请求: GET /api/me\n";
echo "   状态码: {$httpCode}\n";

if ($httpCode === 401) {
    echo "   ✅ 返回401（需要认证），这是预期的\n";

    // 解析响应结构
    $data = json_decode($response, true);
    if ($data) {
        echo "   📋 响应结构分析:\n";
        echo "   - success: " . ($data['success'] ? 'true' : 'false') . "\n";
        echo "   - code: " . ($data['code'] ?? 'N/A') . "\n";
        echo "   - message: " . ($data['message'] ?? 'N/A') . "\n";
        echo "   - has data field: " . (isset($data['data']) ? 'true' : 'false') . "\n";
        echo "   - has timestamp: " . (isset($data['timestamp']) ? 'true' : 'false') . "\n";

        // 检查是否还有嵌套
        if (isset($data['data']) && is_array($data['data'])) {
            $nestedSuccess = isset($data['data']['success']);
            echo "   ⚠️  警告: 检测到嵌套的 success 字段\n" ;
            echo "   - 嵌套层级: " . ($nestedSuccess ? '2层' : '1层') . "\n";
        } else {
            echo "   ✅ 响应结构正确，无嵌套\n";
        }
    } else {
        echo "   ❌ 无法解析JSON响应\n";
    }
} elseif ($httpCode === 200) {
    echo "   ✅ 返回200，解析响应...\n";

    $data = json_decode($response, true);
    if ($data) {
        echo "   📋 响应结构:\n";
        echo "   - success: " . ($data['success'] ? 'true' : 'false') . "\n";
        echo "   - message: " . ($data['message'] ?? 'N/A') . "\n";

        if (isset($data['data']) && is_array($data['data'])) {
            echo "   - data.user: " . (isset($data['data']['user']) ? '存在' : '不存在') . "\n";
            echo "   - data.permissions: " . (isset($data['data']['permissions']) ? '存在' : '不存在') . "\n";

            // 检查嵌套问题
            if (isset($data['data']['success'])) {
                echo "   ❌ 仍有嵌套问题！\n";
            } else {
                echo "   ✅ 数据结构正确，无嵌套\n";
            }
        } else {
            echo "   ❌ data 字段不存在或格式错误\n";
        }
    } else {
        echo "   ❌ 无法解析JSON响应\n";
    }
} else {
    echo "   ❌ 意外状态码: {$httpCode}\n";
    echo "   响应内容: " . substr($response, 0, 200) . "...\n";
}

echo "\n2. 修复建议:\n";
echo "   如果仍有嵌套问题，可能的原因:\n";
echo "   - 中间件包装了响应\n";
echo "   - API资源转换器\n";
echo "   - 其他响应处理逻辑\n";

echo "\n3. 前端访问方式:\n";
echo "   response.data.user (用户信息)\n";
echo "   response.data.permissions (权限列表)\n";

echo "\n🎯 测试完成!\n";
